package com.example.user_service.service;

import com.example.user_service.config.Tel;
import com.example.user_service.dao.UserInsert;
import com.example.user_service.dao.UserSelect;
import com.example.user_service.dao.UserUpdate;
import com.example.user_service.return_data.Mall_Data;
import com.example.user_service.service.qt.Goodsservcie;
import com.example.user_service.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
public class Gservice {
    @Autowired
    UserSelect userSelect;
    @Autowired
    UserInsert userInsert;
    @Autowired
    UserUpdate userUpdate;
    @Autowired
    Tel tel;
    @Autowired
    @Qualifier("template")
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    Goodsservcie goodsservcie;
   @Autowired
   Mall_Data mall_data;
    /**
     * @param administrator
     * @return
     * @methd 检验管理员登录
     */
    public int login_Administrator(Administrator administrator,HttpServletResponse response) {
        administrator=userSelect.login_Administrator(administrator);
        if (administrator!=null &&jq(administrator.getId(),response)){
            return administrator.getId();
        }


        return -1;
    }

    /**
     * @param tel
     * @return
     * @methd 调用发送短信的
     */
    public String getcode(String tel) {
        //省点钱 暂时不用重載的方法
        String code = this.tel.sendtel(tel);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(tel, code.trim(), 2, TimeUnit.MINUTES);
        return code;
    }

    /**
     * @param tel
     * @param code
     * @return
     * @检验验证码和手机是否对的上
     */
    public boolean iscode(String tel, String code) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String s = (String) valueOperations.get(tel);
        System.out.println(code);
        System.out.println(s);
        return s == null ? false : s.equals(code) ? true : false;
    }

    /**
     * 校验手机号是否被注册
     *
     * @param tel
     * @return
     */
    public boolean istel(String tel) {
        return userSelect.login_istel(tel) == 0 ? false : true;
    }

    /**
     * 校验姓名是否被注册
     *
     * @param name
     * @return
     */
    public boolean isaccount(String name) {
        return userSelect.login_isname(name) == 0 ? true : false;
    }

    /**
     * 用来插入的新会员
     *
     * @param tel
     * @param zsname
     * @param idcred
     * @param account
     * @param pawd
     * @return
     */
    @Transactional
    public boolean insert(String tel, String zsname, String idcred, String account, String pawd) {
        //插入登录信息
        Integer i1 = userInsert.insert_user_login(tel, account, pawd, idcred);

        // 查询userid
        Integer userid = userSelect.insert_select_userid(tel);
        System.out.println(userid);

        //新增用户
        Integer i = userInsert.insert_user_data(userid, account, zsname);
        //插入会员信息
        Integer i2 = userInsert.insert_user_menber(userid, UUID.randomUUID() + "");
        if (i == null || i1 == null || i2 == null) {
            throw new RuntimeException();
        } else {
            return true;
        }
    }

    public int getuserid(String tel) {
        Integer integer = userSelect.insert_select_userid(tel);
        return integer != 0 ? integer : -1;
    }

    @Transactional
    public int is_login(String name, String pawd,HttpServletResponse response) {

        String email = ".com";
        String tel = "^1[0-9]{10}$";
 /*       Pattern compile = Pattern.compile(email);
        Matcher matcher = compile.matcher(name);*/
        if (name.length() == 11 && Pattern.matches(tel, name)) {
            UserVO tel1 = userSelect.is_login(name, pawd, "tel");
            System.out.println("---------------运行了手机检测");
            if (tel1 != null && jq(tel1.getUser_id(),response)) {
                userUpdate.update_login_time(tel1.getUser_id());
                return tel1.getUser_id();
            }
        } else if (Pattern.matches(email, name)) {
            UserVO email1 = userSelect.is_login(name, pawd, "email");
            System.out.println("---------------运行了邮箱");
            if (email1 != null && jq(email1.getUser_id(),response)) {
                userUpdate.update_login_time(email1.getUser_id());
                return email1.getUser_id();
            }
        } else {
            System.out.println("---------------运行了账号");
            UserVO account = userSelect.is_login(name, pawd, "account");
            if (account != null && jq(account.getUser_id(),response)) {
                userUpdate.update_login_time(account.getUser_id());
                return account.getUser_id();
            }
        }
        //以防万一
        UserVO tel1 = userSelect.is_login(name, pawd, "tel");

        if (tel1 != null && jq(tel1.getUser_id(),response)) {
            userUpdate.update_login_time(tel1.getUser_id());
            return tel1.getUser_id();
        }
        UserVO email1 = userSelect.is_login(name, pawd, "email");
        if (email1 != null && jq(email1.getUser_id(),response)) {
            userUpdate.update_login_time(email1.getUser_id());
            return email1.getUser_id();
        }
        UserVO account = userSelect.is_login(name, pawd, "account");

        if (account != null && jq(account.getUser_id(),response)) {
            userUpdate.update_login_time(account.getUser_id());
            return account.getUser_id();
        }

        return -1;
    }

    /**
     * 登录授权
     *
     * @param userid
     * @return
     */
    public Boolean jq(int userid,HttpServletResponse response) {
        //  Mall_Data forObject = restTemplate.getForObject("http://POWERSERVICE/authorization?userid=" + userid, Mall_Data.class);
        Mall_Data forObject = goodsservcie.authorization(userid);
        //颁发token,并且保存在浏览器cookie中
        String token= (String) forObject.get("data");
        if (!token.isEmpty()){
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(3600);
            cookie.setDomain("localhost");
            cookie.setPath("/");
            response.addCookie(cookie);
        }

        return Integer.parseInt(forObject.get("code").toString()) == 200 ? true : false;
    }

    public List<Integer> getmy_tracks(int userid) {
        return userSelect.getmy_tracks(userid);
    }

    public Mall_Data getmiaosha(int goodsid) {
        Date date = new Date();
        //查询未来时间内的活动
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        Miaosha getmiaosha = userSelect.getmiaosha(goodsid, format);
        System.out.println(getmiaosha);
        if (getmiaosha == null) return new Mall_Data().setcode(-1);
        try {
            //开始时间
            Date parse = simpleDateFormat.parse(getmiaosha.getMiao_time());
            //开始时间在现在时间之前 活动已经开始
            if (parse.before(date)) {
                return mall_data.setcode(1).setdata(getmiaosha);
            } else {
                return mall_data.setcode(2).setdata(getmiaosha);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Mall_Data().setcode(-1);
    }
}
